<template>
  <div class="xh-user">
    <div class="xh-user__hd"> 部门</div>
    <div class="xh-user__bd">
      <el-autocomplete v-model="searchInput"
                       :disabled="disabled"
                       :popper-append-to-body="false"
                       :fetch-suggestions="searchListDept"
                       placeholder="请输入内容"
                       @select="searchSelect">
        <template v-slot:default="{ item }">
          <span>{{ item[config.label] }}</span>
          <!-- <span style="color: #999;">{{ `(${ item.deptName || ''}${item.deptName ? '-' : ''}${item.post || '无'})` }}</span> -->
        </template>
      </el-autocomplete>
      <div class="search-list">
        <el-breadcrumb style="padding: 5px 0;" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
            <a href="javascript:;" @click="breadcrumbBtn(item, index)">
              {{ item.label }}
            </a>
          </el-breadcrumb-item>
        </el-breadcrumb>
        <div v-if="currentBreadcrumbItem" class="xh-user__list">
          <el-checkbox v-if="!radio" v-model="allChecked" :disabled="disabled" style="line-height: 30px;"
                       @change="handleCheckAllDept">
            全选
          </el-checkbox>
          <WkDepCheckbox ref="depCheckboxRef" :radio="radio" :disabled="disabled"
                         :dataList="currentBreadcrumbItem.deptList"
                         :selectedDataList="deptSelectedList"
                         :props="props"
                         @selectedChange="checkboxChange"
                         @allSelectFlagChange="onAllSelect"
                         @childrenClick="childrenDebounceClick"/>
        </div>
      </div>
      <div class="xh-user__ft">
        <span class="select-info">已选择
          <span class="select-info--num">
          {{ deptSelectedList ? deptSelectedList.length : 0 }}
          </span>
          项
        </span>
        <el-button link @click="clearAll">清空</el-button>
      </div>
    </div>
  </div>
</template>


<script setup>
import {
  hrmDeptQueryTreeListAPI
} from '/src/api/hrm/dept.js'
import {depListAPI} from '/src/api/common.js'

import WkDepCheckbox from '@/szcomponent/NewCom/SzDeptUserComp/WkDepSelect/src/WkDepCheckbox.vue'

import PinyinMatch from 'pinyin-match'
import merge from '/src/utils/merge.js'
import {debounce} from 'throttle-debounce'

const DefaultWkDep = {
  value: 'deptId',
  label: 'name',
  // 默认的搜索人资和管理端人员请求
  dataType: 'manage' // 部门的 value label 一致，用 dataType 区分 manage hrm
}

defineOptions({
  name: 'WkDep', // 新建 dep
  inheritAttrs: false,
})


const props = defineProps({
  // 是否单选
  radio: {
    type: Boolean,
    default: true
  },
  // 用来进入到指定的部门
  optionsDeptList: Array,
  deptSelectedList: Array,
  // 取值字段
  props: {
    type: Object,
    default: () => {
      return {}
    }
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits([ 'update:deptSelectedList'])

const optionData = reactive({
  searchInput: '',

  // 面包屑
  breadcrumbList: [],

  // 当前面包屑
  currentBreadcrumbItem: null,
  // 全选
  allChecked: false
})

const {
  searchInput, breadcrumbList,
  currentBreadcrumbItem, allChecked
} = toRefs(optionData)

const config = computed(() => {
  return merge({...DefaultWkDep}, props.props || {})
})

watch(() => optionData.breadcrumbList, (val) => {
  optionData.currentBreadcrumbItem = optionData.breadcrumbList[optionData.breadcrumbList.length - 1]
}, {
  deep: true
})
watch(() => props.optionsDeptList, (val) => {
  // 如果传入了optionDeptList，此时意味着使用外部传入的部门列表，在这里请求部门的人员列表
  if (props.optionsDeptList) {
    getDepUserList(0, props.optionsDeptList)
  } else {
    requestDepList()
  }
}, {
  immediate: true
})


/**
 * 列效果进行搜索
 * todo whf 目前只能搜索一级，最好要支持子树的搜索
 */
function searchListDept(queryString, cb) {
  console.log("searchListDept", queryString, cb)
  const deptList = optionData.currentBreadcrumbItem.deptList
  console.log("deptList", deptList)
  if (deptList && deptList.length > 0) {
    const currentList = deptList
    if (queryString) {
      cb(currentList.filter(item => PinyinMatch.match(item[config.value.label] || '', queryString)))
    } else {
      cb(currentList)
    }
  }
}

const depCheckboxRef = ref()
/**
 * 搜索选择
 */
function searchSelect(item) {
  depCheckboxRef.value && depCheckboxRef.value.searchSelect(item)
}

/**
 * 勾选
 */
function checkboxChange(val) {
  nextTick(() => {
    emits('update:deptSelectedList', val)
  })
}

/**
 * 全部勾选
 */
function handleCheckAllDept(val) {
  if (depCheckboxRef.value) {
    depCheckboxRef.value.handleCheckAllChange(val)
  }
}

/**
 * 用户全选
 */
function onAllSelect(allChecked) {
  if (optionData.allChecked != allChecked) {
    optionData.allChecked = allChecked
  }
}

/**
 * 清空全部
 */
function clearAll() {
  // emits('input', [])
  emits('update:deptSelectedList', [])
}

/**
 * 获取部门员工数据
 */
function getDepUserList(deptId, data) {
  console.log("getDepUserList", deptId, data)
  if (deptId == 0) {
    optionData.breadcrumbList = [{label: '全部', deptList: data, employeeList: []}]
  } else {
    optionData.breadcrumbList.push({label: data.name, deptList: data.children, employeeList: []})
  }
}

/**
 * 请求部门数据
 */
function requestDepList() {
  console.log("requestDepList")

  const request = config.value.dataType === 'hrm' ? hrmDeptQueryTreeListAPI : depListAPI
  request({
    type: 'tree'
  }).then(res => {
    console.log("requestDepList",res.data.data)
    getDepUserList(0, res.data.data || [])
  }).catch(() => {
  })
}


const childrenDebounceClick = debounce(300, childrenClick)

/**
 * 下一级
 */
function childrenClick(item) {
  console.log("childrenClick,", item)
  if (!props.radio) {
    optionData.allChecked = false
  }
  getDepUserList(item.deptId, item)
}


/**
 * 面包屑点击
 */
function breadcrumbBtn(item, index) {
  if (index + 1 <= optionData.breadcrumbList.length - 1) {
    optionData.breadcrumbList.splice(index + 1, optionData.breadcrumbList.length - 1)
  }
}
</script>

<style lang="scss" scoped>
/* 选择员工 */
.search-list {
  padding: 5px 0;
  height: 248px;
  overflow: auto;
}

.xh-user {
  color: #333;
  font-size: 13px;

  &__hd {
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid $xr-border-line-color;
  }

  &__bd {
    padding: 10px 12px;
  }

  &__ft {
    padding: 5px 12px;
    background: #f7f8fa;
    border-top: 1px solid $xr-border-line-color;

    .el-button {
      font-size: 12px;
    }
  }

  &__list {
    height: calc(100% - 24px);
    overflow-y: auto;
    padding-left: 5px;
  }
}

// 选择信息
.select-info {
  display: inline-block;
  width: calc(100% - 30px);

  &--num {
    color: $xr-color-primary;
  }
}

// check样式
.el-checkbox-group {
  overflow-x: hidden;
}

.el-checkbox {
  :deep(.el-checkbox__label) {
    color: #333;
  }
}

.all-check {
  display: inline-block;
  padding: 5px 0;
}

.el-autocomplete {
  width: 100%;

  :deep( .el-input__inner ) {
    background-color: #F4F4F4;
    border: none;
  }
}
</style>
